# -*- coding: UTF-8 -*- 
from BeautifulSoup import BeautifulSoup
import urllib2
from deal_info_web import *

def deal_city(tuan, city, ename):
    (f_id, d_id, orig) = judge_begin(tuan, city)

    f_url = urllib2.urlopen('http://www.24quan.com/city.php?ename=%s&r=' % (ename))

    soup = BeautifulSoup(f_url.read())

    f_xml = open('%sxml/%s_%s.xml' % (get_home_dir(), tuan, city), 'w')
    
    f_xml.write('<deals>\n')
    
    deal_id = soup.find(attrs={'class':'deal-today-link'})['href'].replace('/team.php?id=', '')
    if not judge(f_id, d_id, deal_id):
	f_xml.write('\t' + '<deal>\n')
	deal_info_source(f_xml, '24quan', '24券'.decode('utf-8'), 'http://www.24quan.com/', 'http://www.24quan.com/')

	f_xml.write('\t' * 2 + '<city>%s</city>\n' % city)

	deal_info_add(f_xml, 'id', deal_id, 2)
	deal_title = soup.find(attrs={'id':'deal-title'}).contents[0]
	deal_info_add(f_xml, 'name', deal_title, 2)
	deal_info_cats(f_xml, deal_title)
	deal_vendor_name = soup.find(attrs={'id':'side-business'}).h2.contents[0]
	deal_info_vendor(f_xml, deal_vendor_name)
	deal_info_time(f_xml)
	deal_value = soup.find(attrs={'class':'deal-discount'})('tr')[1]('td')[0].contents[0].replace('￥'.decode('utf-8'), '')
	deal_info_add(f_xml, 'o_price', deal_value, 2)
	deal_price = soup.find(attrs={'class':'deal-price'}).strong.contents[0].replace('￥'.decode('utf-8'), '')
	deal_info_add(f_xml, 'c_price', deal_price, 2)
	deal_info_discount_and_save_money(f_xml, deal_price, deal_value)
	deal_img = soup.find(attrs={'class':'deal-buy-cover-img'}).img['src']
	deal_info_img(f_xml, deal_img)
	deal_url = 'http://www.24quan.com/team.php?id=%s' % (deal_id)
	deal_info_add(f_xml, 'url', deal_url, 2)

	f_xml.write('\t' + '</deal>\n')

    f_xml.write(orig[8 : ])

    f_xml.close()
    f_id.close()

    judge_end(tuan, city)



deal_city('24quan', 'beijing', 'bj')
deal_city('24quan', 'shanghai', 'sh')
deal_city('24quan', 'wuhan', 'wh')
deal_city('24quan', 'changsha', 'cs')
deal_city('24quan', 'shenzhen', 'sz')
deal_city('24quan', 'zhengzhou', 'zz')
